﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>客户订单查询</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <style>
        .search-container {
            background: #fff;
            padding: 15px;
            margin-bottom: 10px;
            border-radius: 2px;
            box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
        }
        .table-container {
            background: #fff;
            border-radius: 2px;
            box-shadow: 0 1px 2px 0 rgba(0,0,0,.05);
        }
        .search-form .layui-form-item {
            margin-bottom: 15px;
        }
        .toolbar {
            padding: 15px;
            border-bottom: 1px solid #e6e6e6;
        }
        .order-status-0 {
            color: #FF9800;
        }
        .order-status-1 {
            color: #4CAF50;
        }
        .order-status-2 {
            color: #2196F3;
        }
        .order-status-3 {
            color: #009688;
        }
        .order-status-4 {
            color: #F44336;
        }
    </style>
</head>
<body>
    <div class="layui-container-fluid">
        <!-- 搜索条件区域 -->
        <div class="search-container">
            <form class="layui-form search-form" lay-filter="searchForm">
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">订单编码</label>
                            <div class="layui-input-block">
                                <input type="text" name="orderCode" placeholder="请输入订单编码" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">客户名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="customerName" placeholder="请输入客户名称" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">产品编号</label>
                            <div class="layui-input-block">
                                <input type="text" name="productCode" placeholder="请输入产品编号" class="layui-input">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">产品名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="productName" placeholder="请输入产品名称" class="layui-input">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">订单状态</label>
                            <div class="layui-input-block">
                                <select name="orderStatus">
                                    <option value="">全部状态</option>
                                    <option value="0">待处理</option>
                                    <option value="1">已确认</option>
                                    <option value="2">生产中</option>
                                    <option value="3">已完成</option>
                                    <option value="4">已取消</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">订货日期</label>
                            <div class="layui-input-block">
                                <input type="text" name="orderDateRange" placeholder="开始日期 - 结束日期" class="layui-input" id="orderDateRange">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <label class="layui-form-label">交货日期</label>
                            <div class="layui-input-block">
                                <input type="text" name="deliveryDateRange" placeholder="开始日期 - 结束日期" class="layui-input" id="deliveryDateRange">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-form-item">
                            <div class="layui-input-block" style="text-align: right; margin-left: 0;">
                                <button type="button" class="layui-btn" lay-submit lay-filter="searchBtn">
                                    <i class="layui-icon layui-icon-search"></i> 搜索
                                </button>
                                <button type="reset" class="layui-btn layui-btn-primary">
                                    <i class="layui-icon layui-icon-refresh"></i> 重置
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <!-- 表格区域 -->
        <div class="table-container">
            <!-- 工具栏 -->
            <div class="toolbar">
                <button type="button" class="layui-btn layui-btn-sm" id="addBtn">
                    <i class="layui-icon layui-icon-add-1"></i> 新增
                </button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="modifyBtn">
                    <i class="layui-icon layui-icon-edit"></i> 修改
                </button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="deleteBtn">
                    <i class="layui-icon layui-icon-delete"></i> 删除
                </button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-warm" id="exportBtn">
                    <i class="layui-icon layui-icon-export"></i> 导出
                </button>
                
                <div class="layui-btn-group" style="float: right;">
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="refreshBtn">
                        <i class="layui-icon layui-icon-refresh"></i>
                    </button>
                    <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="settingBtn">
                        <i class="layui-icon layui-icon-set"></i>
                    </button>
                </div>
            </div>

            <!-- 数据表格 -->
            <table class="layui-hide" id="customerOrderTable" lay-filter="customerOrderTable"></table>
        </div>
    </div>

    <!-- 操作列模板 -->
    <script type="text/html" id="operationTpl">
        <a class="layui-btn layui-btn-xs" lay-event="edit">
            <i class="layui-icon layui-icon-edit"></i> 修改
        </a>
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">
            <i class="layui-icon layui-icon-delete"></i> 删除
        </a>
    </script>

    <!-- 订单状态模板 -->
    <script type="text/html" id="statusTpl">
        {{# if(d.orderStatus === 0){ }}
            <span class="order-status-0">待处理</span>
        {{# } else if(d.orderStatus === 1){ }}
            <span class="order-status-1">已确认</span>
        {{# } else if(d.orderStatus === 2){ }}
            <span class="order-status-2">生产中</span>
        {{# } else if(d.orderStatus === 3){ }}
            <span class="order-status-3">已完成</span>
        {{# } else if(d.orderStatus === 4){ }}
            <span class="order-status-4">已取消</span>
        {{# } else { }}
            <span>未知状态</span>
        {{# } }}
    </script>

    <script>
        layui.use(['table', 'form', 'laydate', 'layer'], function() {
            var table = layui.table;
            var form = layui.form;
            var laydate = layui.laydate;
            var layer = layui.layer;

            // 初始化日期范围选择器
            laydate.render({
                elem: '#orderDateRange',
                range: true,
                type: 'date'
            });

            laydate.render({
                elem: '#deliveryDateRange',
                range: true,
                type: 'date'
            });

            // 初始化表格 - 使用服务端分页
            var tableIns = table.render({
                elem: '#customerOrderTable',
                url: '/CustomerOrder/GetCustomerOrderList', // 接口地址
                method: 'GET',
                cols: [[ 
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'orderNumber', title: '订单编码', width: 150, sort: true},
                    {field: 'customerCode', title: '客户编码', width: 120},
                    {field: 'customerName', title: '客户名称', width: 180},
                    {field: 'productCode', title: '产品编号', width: 150},
                    {field: 'productName', title: '产品名称', width: 180},
                    {field: 'orderDate', title: '订货日期', width: 120, sort: true, templet: function(d){
                        if(d.orderDate) {
                            return new Date(d.orderDate).toLocaleDateString();
                        }
                        return '';
                    }},
                    {field: 'deliveryDate', title: '交货日期', width: 120, sort: true, templet: function(d){
                        if(d.deliveryDate) {
                            return new Date(d.deliveryDate).toLocaleDateString();
                        }
                        return '';
                    }},
                    {field: 'specificationModel', title: '规格型号', width: 120},
                    {field: 'orderQuantity', title: '订货数量', width: 120, sort: true},
                    {field: 'unit', title: '单位', width: 80},
                    {field: 'orderStatus', title: '订单状态', width: 120, templet: '#statusTpl'},
                    {field: 'qualityRequirement', title: '质量要求', width: 200},
                    {title: '操作', width: 150, templet: '#operationTpl', fixed: 'right', align: 'center'}
                ]],
                skin: 'line',
                even: true,
                page: true,
                limit: 10,
                limits: [10, 20, 50, 100],
                height: 'full-150',
                parseData: function(res) {
                    // 解析分页数据
                    return {
                        "code": 0,
                        "msg": "",
                        "count": res.pageCount,
                        "data": res.listDate
                    };
                },
                request: {
                    pageName: 'page',
                    limitName: 'limit'
                },
                where: {
                    orderCode: '',
                    customerName: '',
                    productCode: '',
                    productName: '',
                    orderStatus: null,
                    startDate: '',
                    endDate: ''
                }
            });

            // 获取查询条件
            function getSearchParams() {
                var formData = form.val('searchForm');
                var params = {
                    orderCode: formData.orderCode || '',
                    customerName: formData.customerName || '',
                    productCode: formData.productCode || '',
                    productName: formData.productName || '',
                    orderStatus: formData.orderStatus || null,
                    startDate: '',
                    endDate: ''
                };

                // 处理订货日期范围
                if (formData.orderDateRange) {
                    var dateRange = formData.orderDateRange.split(' - ');
                    if (dateRange.length === 2) {
                        params.startDate = dateRange[0];
                        params.endDate = dateRange[1];
                    }
                }

                return params;
            }

            // 搜索功能
            form.on('submit(searchBtn)', function(data) {
                var searchParams = getSearchParams();
                
                // 重新加载表格数据
                table.reload('customerOrderTable', {
                    where: searchParams,
                    page: {
                        curr: 1 // 重新从第1页开始
                    }
                });

                layer.msg('搜索中...', {icon: 16, time: 1000});
                return false;
            });

            // 表格工具栏事件
            $('#addBtn').on('click', function() {
                window.location.href = '/CustomerOrder/CustomerOrderAdd';
            });

            $('#modifyBtn').on('click', function() {
                var checkStatus = table.checkStatus('customerOrderTable');
                if (checkStatus.data.length === 0) {
                    layer.msg('请选择要修改的记录');
                    return;
                }
                if (checkStatus.data.length > 1) {
                    layer.msg('只能选择一条记录进行修改');
                    return;
                }
                
                var selectedData = checkStatus.data[0];
                openEditDialog(selectedData.id, selectedData.orderNumber);
            });

            $('#deleteBtn').on('click', function() {
                var checkStatus = table.checkStatus('customerOrderTable');
                if (checkStatus.data.length === 0) {
                    layer.msg('请选择要删除的记录');
                    return;
                }
                
                // 检查是否有正在处理中的订单
                var processingOrders = checkStatus.data.filter(function(item) {
                    return item.orderStatus > 1; // 状态>1表示正在处理中
                });
                
                if (processingOrders.length > 0) {
                    var processingOrderNumbers = processingOrders.map(function(item) {
                        return item.orderNumber;
                    }).join(', ');
                    layer.msg('以下订单正在处理中，无法删除：' + processingOrderNumbers, {icon: 2, time: 3000});
                    return;
                }
                
                var orderNumbers = checkStatus.data.map(function(item) {
                    return item.orderNumber;
                }).join('、');
                
                layer.confirm('确定删除选中的 ' + checkStatus.data.length + ' 条订单记录吗？<br><br>订单编码：' + orderNumbers, {
                    icon: 3,
                    title: '批量删除确认'
                }, function(index) {
                    // 获取选中的订单ID
                    var ids = checkStatus.data.map(function(item) {
                        return item.id;
                    });
                    
                    // 调用删除API
                    $.ajax({
                        url: '/CustomerOrder/DeleteCustomerOrders',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(ids),
                        beforeSend: function() {
                            layer.msg('正在删除...', {icon: 16, time: 0});
                        },
                        success: function(response) {
                            layer.closeAll('msg');
                            console.log('删除响应:', response);
                            
                            if (response && (response.Success || response.success)) {
                                layer.msg('删除成功！', {
                                    icon: 1,
                                    time: 2000
                                }, function() {
                                    // 刷新表格
                                    table.reload('customerOrderTable');
                                });
                            } else {
                                var errorMsg = (response && (response.Message || response.message)) ? (response.Message || response.message) : '删除失败';
                                layer.msg(errorMsg, {
                                    icon: 2,
                                    time: 3000
                                });
                            }
                        },
                        error: function(xhr, status, error) {
                            layer.closeAll('msg');
                            console.error('删除AJAX错误:', {xhr: xhr, status: status, error: error});
                            var errorMsg = '网络错误，删除失败';
                            if (xhr.responseText) {
                                try {
                                    var errorResponse = JSON.parse(xhr.responseText);
                                    errorMsg = errorResponse.Message || errorMsg;
                                } catch (e) {
                                    errorMsg = xhr.responseText;
                                }
                            }
                            layer.msg(errorMsg, {
                                icon: 2,
                                time: 3000
                            });
                        }
                    });
                    
                    layer.close(index);
                });
            });

            $('#exportBtn').on('click', function() {
                layer.msg('导出Excel功能');
            });

            $('#refreshBtn').on('click', function() {
                table.reload('customerOrderTable');
                layer.msg('刷新成功');
            });

            // 行工具事件
            table.on('tool(customerOrderTable)', function(obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    openEditDialog(data.id, data.orderNumber);
                } else if (obj.event === 'delete') {
                    // 检查订单状态
                    if (data.orderStatus > 1) {
                        layer.msg('订单 "' + data.orderNumber + '" 正在处理中，无法删除', {icon: 2});
                        return;
                    }
                    
                    layer.confirm('确定删除订单 "' + data.orderNumber + '" 吗？', {
                        icon: 3,
                        title: '删除确认'
                    }, function(index) {
                        // 调用删除API
                        $.ajax({
                            url: '/CustomerOrder/DeleteCustomerOrders',
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify([data.id]),
                            beforeSend: function() {
                                layer.msg('正在删除...', {icon: 16, time: 0});
                            },
                            success: function(response) {
                                layer.closeAll('msg');
                                console.log('删除响应:', response);
                                
                                if (response && (response.Success || response.success)) {
                                    obj.del(); // 删除表格行
                                    layer.msg('删除成功！', {
                                        icon: 1,
                                        time: 2000
                                    });
                                } else {
                                    var errorMsg = (response && (response.Message || response.message)) ? (response.Message || response.message) : '删除失败';
                                    layer.msg(errorMsg, {
                                        icon: 2,
                                        time: 3000
                                    });
                                }
                            },
                            error: function(xhr, status, error) {
                                layer.closeAll('msg');
                                console.error('删除AJAX错误:', {xhr: xhr, status: status, error: error});
                                var errorMsg = '网络错误，删除失败';
                                if (xhr.responseText) {
                                    try {
                                        var errorResponse = JSON.parse(xhr.responseText);
                                        errorMsg = errorResponse.Message || errorMsg;
                                    } catch (e) {
                                        errorMsg = xhr.responseText;
                                    }
                                }
                                layer.msg(errorMsg, {
                                    icon: 2,
                                    time: 3000
                                });
                            }
                        });
                        
                        layer.close(index);
                    });
                }
            });

            // 打开修改弹窗的函数
            function openEditDialog(orderId, orderNumber) {
                console.log('准备打开修改弹窗，订单ID：', orderId, '订单编号：', orderNumber);
                
                if (!orderId) {
                    layer.msg('订单ID不能为空', {icon: 2});
                    return;
                }
                
                var editUrl = '/CustomerOrder/CustomerOrderEdit?id=' + orderId;
                console.log('修改页面URL：', editUrl);
                
                layer.open({
                    type: 2,
                    title: '修改客户订单 - ' + orderNumber,
                    area: ['90%', '90%'],
                    content: editUrl,
                    maxmin: true,
                    success: function(layero, index) {
                        // 弹窗打开成功后的回调
                        console.log('修改弹窗已成功打开，订单ID：', orderId);
                        console.log('弹窗层对象：', layero);
                        console.log('弹窗索引：', index);
                    },
                    cancel: function(index, layero) {
                        console.log('用户点击了关闭按钮');
                        return true; // 返回true表示允许关闭
                    },
                    end: function() {
                        // 弹窗关闭后刷新表格数据
                        console.log('修改弹窗已关闭，刷新表格数据');
                        table.reload('customerOrderTable');
                        layer.msg('已刷新订单列表');
                    }
                });
            }

            // 重置表单
            $('button[type="reset"]').on('click', function() {
                $('.search-form')[0].reset();
                form.render(); // 重新渲染表单
                
                // 重置表格查询条件
                table.reload('customerOrderTable', {
                    where: {
                        orderCode: '',
                        customerName: '',
                        productCode: '',
                        productName: '',
                        orderStatus: null,
                        startDate: '',
                        endDate: ''
                    },
                    page: {
                        curr: 1
                    }
                });
                
                layer.msg('重置成功');
            });
        });
    </script>
</body>
</html>


